const moment = require('moment');
const COS = require('cos-nodejs-sdk-v5');
const STS = require('qcloud-cos-sts');


var config = {
    secretId: "AKIDacOtBFLv7T5TghNTZR5Tbgw87sPph4nJ", // 固定密钥
    secretKey: "Zo4ACzvnV5ZDheNp1yg8wT1Pbu52kEUB", // 固定密钥
    proxy: '',
    durationSeconds: 1800, // 密钥有效期
    // 放行判断相关参数
    bucket: 'beamuse-1301730110', // 换成你的 bucket
    region: 'ap-shanghai', // 换成 bucket 所在地区
    allowPrefix: '*' // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
};

module.exports = {



    getAuthorization: async(req, res, next) => {
        var shortBucketName = config.bucket.substr(0, config.bucket.lastIndexOf('-'));
        var appId = config.bucket.substr(1 + config.bucket.lastIndexOf('-'));
        var policy = {
            'version': '2.0',
            'statement': [{
                'action': [
                    // 简单上传
                    'name/cos:PutObject',
                    'name/cos:PostObject',
                    // 分片上传
                    'name/cos:InitiateMultipartUpload',
                    'name/cos:ListMultipartUploads',
                    'name/cos:ListParts',
                    'name/cos:UploadPart',
                    'name/cos:CompleteMultipartUpload',
                ],
                'effect': 'allow',
                'principal': { 'qcs': ['*'] },
                'resource': [
                    'qcs::cos:' + config.region + ':uid/' + appId + ':prefix//' + appId + '/' + shortBucketName + '/' + config.allowPrefix,
                ],
            }],
        };
        STS.getCredential({
            secretId: config.secretId,
            secretKey: config.secretKey,
            proxy: config.proxy,
            durationSeconds: config.durationSeconds,
            region: config.region,
            policy: policy,
        }, function(err, credential) {
            console.log('getCredential:');
            console.log(JSON.stringify(policy, null, '    '));
            console.log(err || credential);
            res.ok('成功', credential)
        });
    }
}